const _ = require("lodash");
// 解决pkg qiniu报错
const qiniu = {
  auth: {
    digest: require("qiniu/qiniu/auth/digest")
  },
  cdn: require("qiniu/qiniu/cdn.js"),
  form_up: require("qiniu/qiniu/storage/form.js"),
  resume_up: require("qiniu/qiniu/storage/resume.js"),
  rs: require("qiniu/qiniu/storage/rs.js"),
  fop: require("qiniu/qiniu/fop.js"),
  conf: require("qiniu/qiniu/conf.js"),
  rpc: require("qiniu/qiniu/rpc.js"),
  util: require("qiniu/qiniu/util.js"),
  zone: require("qiniu/qiniu/zone.js")
};
const bcrypt = require("bcryptjs");
const config = require("./../config");

module.exports = {
  /**
   * 获取config配置
   */
  config(key) {
    return _.get(config, key);
  },

  /**
   * 获取redis键
   * @param {*} key
   */
  getVersionKey(key) {
    return `baas:${config.version}:${key}`;
  },

  /**
   * 判断字符串是否是JSON
   * @param {*} str
   */
  isStrToJson(str) {
    try {
      JSON.parse(str);
    } catch (err) {
      return false;
    }
    return true;
  },

  /**
   * 判断能否转化成JSON字符串
   * @param {*} str
   */
  isJsonToStr(str) {
    try {
      JSON.stringify(str);
    } catch (err) {
      return false;
    }
    return true;
  },

  /**
   * 七牛图片上传
   * @param  {[type]}
   * @param  {[type]}
   * @return {[type]}
   */
  async uploadFile(localFile, savename) {
    const mac = new qiniu.auth.digest.Mac(
      config.qiniu.accessKey,
      config.qiniu.secretKey
    );

    /* eslint-disable quotes */
    const options = {
      scope: config.qiniu.bucket + ":" + savename,
      returnBody:
        '{"bucket":"$(bucket)","key":"$(key)","etag":"$(etag)","fname":"$(fname)","fsize":"$(fsize)","mimeType":$(mimeType),"uuid":"$(uuid)","ext":"$(ext)"}',
      callbackBodyType: "application/json"
    };
    /* eslint-disable quotes */

    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
    const qiniuConfig = new qiniu.conf.Config();
    const formUploader = new qiniu.form_up.FormUploader(
      Object.assign(qiniuConfig, {
        zone: config.qiniu.zone
      })
    );
    const putExtra = new qiniu.form_up.PutExtra();

    return new Promise((resolve, reject) => {
      formUploader.putFile(
        uploadToken,
        savename,
        localFile,
        putExtra,
        (respErr, respBody, respInfo) => {
          if (respErr) {
            reject(respErr);
          }
          if (respInfo.statusCode === 200) {
            resolve(respBody.key);
          } else {
            reject(respBody);
          }
        }
      );
    });
  },

  /**
   * 根据关联关系生成bookshelf model
   * @param  appid		当前应用appid
   * @param  appkey		当前应用appkey
   * @param  dev		当前应用dev
   * @param  database		当前数据库名称
   * @param  table		当前数据表名称
   * @param  tables		所有数据表配置
   * @param  relations	所有数据表关联
   * @param  bookshelf  	bookshelf
   * @return 		 		Model
   */
  getModel(appid, appkey, dev, database, table, tables, relations, bookshelf) {
    const options = {
      tableName: `${database}.${table}`,
      hasTimestamps: true,
      softDelete: true,
      appid: appid,
      appkey: appkey,
      dev: dev
    };
    const that = this;

    for (const key in tables) {
      if (tables[key].name === table) {
        // 隐藏字段
        if (tables[key].hidden) {
          options.hidden = this.strToArray(tables[key].hidden);
        }
        // 自增主键uuid
        options.uuid = tables[key].uuid;
      }
    }

    for (const key in relations) {
      if (table === relations[key].table) {
        let target = relations[key].target;
        const targeted = relations[key].targeted;

        options[targeted || target] = function() {
          if (target.indexOf(".") !== -1) {
            const targets = target.split(".");
            database = targets[0];
            target = targets[1];
          }

          return this[relations[key].relation](
            that.getModel(
              appid,
              appkey,
              dev,
              database,
              target,
              tables,
              relations,
              bookshelf
            ),
            relations[key].foreign_key,
            relations[key].foreign_key_target
          );
        };
      }
    }

    return bookshelf.Model.extend(options, {});
  },

  /**
   * 获取qb，输出到前端
   * @param {*} qb
   */
  getStatement(qb) {
    const statements = [];
    for (const key in qb._statements) {
      try {
        statements.push(JSON.parse(JSON.stringify(qb._statements[key])));
      } catch (err) {}
    }
    return statements;
  },

  /**
   * 字符串转数组
   * @param  str
   * @param  step
   * @return array
   */
  strToArray(str, step = ",") {
    if (!str) return [];
    if (str instanceof Array) return;
    if (str.indexOf(step) !== -1) {
      return str.split(step);
    } else {
      return [str];
    }
  },

  /**
   * bcrypt加密
   * @param {*} val
   */
  bcrypt(val) {
    return bcrypt.hash(val, 12);
  }
};
